<?php
class Config extends CApplicationComponent
{
public $cache = 0;
public $dependency = null;
protected $data = array();

    public function init()
    {
        $conn = $this->getDbConnection();
        $config = $conn->createCommand("SELECT * FROM {{config}}")->queryAll();
        foreach($config as $c)
        {
            $this->data[$c['param']] = $c['value'] === '' ? $c['default'] : $c['value'];
        }
        parent::init();
    }

    protected function getDbConnection()
    {
        if(isset($this->cache))
        {
            $conn = Yii::app()->db->cache($this->cache,$this->dependency);
        }
        else
        {
            $conn = Yii::app()->db;
        }
        return $conn;
    }

    public function get($key)
    {
        if(array_key_exists($key,$this->data))
        {
            return $this->data[$key];
        }
        else
        {
            throw new CException('Undefined parametr',$key);
        }
    }

    public function set($key,$value)
    {
        $model = Config::model()->findByAttributes(array('param'=>$key));
        if(!$model)
        {
            throw new CException('Undefined parametr',$key);
        }

        $model->value = $value;
        if($model->save())
        {
            $this->data[$key] = $value;
        }
    }

    public function add($params)
    {
        if(isset($params[0]) && is_array($params[0]))
        {
            foreach($params as $p)
            {
                $this->createParameter($p);
            }
        }
        elseif($params)
        {
            $this->createParameter($params);
        }
    }

    public function delete($key)
    {
        if(is_array($key))
        {
            foreach($key as $k)
            {
                $this->removeParameter($key);
            }
        }
        elseif($key)
        {
            $this->removeParameter($key);
        }
    }

    protected function createParameter($param)
    {
        if (!empty($param['param']))
        {
            $model = Config::model()->findByAttributes(array('param' => $param['param']));
            if ($model === null)
            {
                $model = new Config();
            }

            $model->param = $param['param'];
            $model->label = isset($param['label']) ? $param['label'] : $param['param'];
            $model->value = isset($param['value']) ? $param['value'] : '';
            $model->default = isset($param['default']) ? $param['default'] : '';
            $model->type = isset($param['type']) ? $param['type'] : 'string';

            $model->save();
        }
    }

    protected function removeParameter($key)
    {
        if (!empty($key))
        {
            $model = Config::model()->findByAttributes(array('param'=>$key));
            if ($model)
            {
                $model->delete();
            }
        }
    }
}